/**
 * 正则
 */
//用户名正则，1到16位（字母，数字，下划线，减号）
var usernamePattern = /^[\u4e00-\u9fa5_a-zA-Z0-9-]{1,16}$/;
//密码强度正则，最少6位，包括至少1个大写字母，1个小写字母，1个数字
var pwdPattern = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/;
/**
 * 查询用户接口
 * @param role
 * @param callback
 */
var num = 1;
var pageSize = 10;
var role = "";
function listUser(role, pageNum, pageSize) {
    $.ajax({
        url: HOST.concat("/users/role?role=" + role + "&pageNum=" + pageNum + "&pageSize=" + pageSize + "&token=" + config.token),
        type: "GET",
        success: function(datas){
			checkLogin(datas);
			console.log(datas);
        	addContent(datas);
        },
        error: function(){
            console.log("请求用户列表错误！");
        },
        dataType: "json",
    })
}

/**
 * 删除用户接口
 * @param username
 * @param callback
 */
function deleteUser(username) {
    var uname=username+"";
    $.ajax({
        url: HOST.concat("/users/username?token=" + config.token),
        type: "DELETE",
        contentType: "application/x-www-form-urlencoded",
        data: {
            "username":uname
        },
        success: function(res){
			checkLogin(res);
            console.log(res);
            //todo;是否能改善reload屏幕闪烁的问题
            window.location.reload();
        },
        error: function () {
            console.log("delete error");
        },
        dataType: "json"
    })
}

/**
 * 用户修改密码接口
 * @param callback
 */
function changePsw(callback){
    var formerPassword=md5($("#old").val()+'scuwsn');
    console.log("oldpas:"+formerPassword)
    var newPassword=md5($("#password").val()+'scuwsn');
    // var formerPassword=md5($("#old").val());
    // var newPassword=md5($("#password").val());
    var data={
        "username": config.username,
        "formerPassword": formerPassword,
        "newPassword": newPassword
    };
    $.ajax({
        async: false,
        type: "PUT",
        url:HOST.concat("/users/username?token="+config.token),
        contentType : "application/x-www-form-urlencoded; charset=utf-8",
        data: data,
        dataType: "json",
        success: callback,
        error: function () {
        }
    })
}

/**
 * 添加用户接口
 * @param callback
 */
function addUser(callback){
    var username=$("#username").val();
    var role=$("#role").val();
    var data={
        username: username,
        role: role,
    };
    $.ajax({
        async: false,
        type: "POST",
        url:HOST.concat("/users?token="+config.token),
        contentType : "application/x-www-form-urlencoded; charset=utf-8",
        data: data,
        dataType: "json",
        success: callback,
        error: function () {
        }
    })
}

function addContent(res){
	if(res.meta.state==="success") {
            var list = res.data;
			if(list.length==0){
				alert("已经是最后一页!");
				num--;
			}else{
				//console.log("有查询记录");
				//console.log(list);
				$("#tbody").empty();
				$("#pageNum").text(num);
				var count = 0;
				for (var p in list) {
				    var item = list[p];//单条数据
					//console.log(item);
				    count++;
				    var username = item["username"];
				    var createTime = item["createTime"];
				    $("#tbody").append("<div class=\"tr clearfix border-bottom-none\">" +
				        // "                  <div class=\"td w10\"> <input type=\"checkbox\"/></div>" +
				        "                  <div class=\"td w20\">" + count + "</div>" +
				        "                  <div class=\"td w30\">" + username + "</div>" +
				        "                  <div class=\"td w30\">" + createTime + "</div>" +
				        "                  <div class=\"td w20\">" +
				        "                      <div style=\"display: inline-block;\" class='myIcon'>" +
				        "                          <a msg=\"确认删除此项吗?\" class=\"button-word2 btn_ajax_confirm\" callback=\"deleteUser(\'" + username + "\')\";>" +
				        "                             <i class=\"fa fa-trash fa-lg\" title=\"删除该用户\"></i>" +
				        "                          </a>" +
				        "                      </div>" +
				        "                  </div>" +
				        "               </div>");
				}
			}
	        
        }
        //查询失败
        else if(res.meta.message!="notlogin"){
            alert("已经是最后一页!");
            num--;
        }
}

function getUsersList(thisRole,num){
	role = thisRole;
	listUser(role,num,pageSize);
}

function adminLastPage(){
	if(num<=1){
		num = 1;
		alert("已经是第一页!");
		$("#pageNum").text(num);
	}else{
		num--;
		getUsersList(role,num);
	}
}

function adminNextPage(){
		num++;
		getUsersList(role,num);
}

function adminFirstPage(){
	num = 1;
	$("#pageNum").text(num);
	getUsersList(role,num);
}

function checkUsername() {
    var username = $("#username").val();
    removeUsernameText();
    if(username==''||username==undefined){
        $("#username").after("<span class='usernameText' style='color:red'>&nbsp;用户名不能为空</span>");
    }else if(username.length>16){
        $("#username").after("<span class='usernameText' style='color:red'>&nbsp;用户名长度大于16位</span>");
    }else if(usernamePattern.test(username)!=true){
        $("#username").after("<span class='usernameText' style='color:red'>&nbsp;用户名格式不规范</span>");
    }else {
        return true;
    }
}

function checkOldPwd() {
    var oldPwd = $("#old").val();
    removeOldPwdText();
    if(oldPwd==''||oldPwd==undefined){
        $("#old").after("<span class='oldPwdText' style='color:red'>&nbsp;旧密码不能为空</span>");
    }else {
        return true;
    }
}

function checkNewPwd() {
    var oldPwd = $("#old").val();
    var newPwd = $("#password").val();
    removeNewPwdText();
    if(newPwd==''||newPwd==undefined){
        $("#password").after("<span class='newPwdText' style='color:red'>&nbsp;新密码不能为空</span>");
    }else if(newPwd.length>16||newPwd.length<6){
        $("#password").after("<span class='newPwdText' style='color:red'>&nbsp;新密码长度不规范</span>");
    }else if(pwdPattern.test(newPwd)!=true){
        $("#password").after("<span class='newPwdText' style='color:red'>&nbsp;新密码格式不规范</span>");
    }else if(newPwd==oldPwd){
        $("#password").after("<span class='newPwdText' style='color:red'>&nbsp;新旧密码不能相同</span>");
    }else {
        return true;
    }
}

function checkConfirmPwd() {
    var confirmPwd = $("#confirmpwd").val();
    var newPwd = $("#password").val();
    removeConfirmPwdText();
    if(confirmPwd==''||confirmPwd==undefined){
        $("#confirmpwd").after("<span class='confirmPwdText' style='color:red'>&nbsp;确认新密码不能为空</span>");
    }else if(confirmPwd!=newPwd){
        $("#confirmpwd").after("<span class='confirmPwdText' style='color:red'>&nbsp;两次输入密码需一致</span>");
    }else {
        return true;
    }
}

//设置一个全局的变量，便于保存验证码
var code;
function createCode(){
    //首先默认code为空字符串
    code = '';
    //设置长度，这里看需求，我这里设置了4
    var codeV = document.getElementById('code');
    //设置随机字符
    $.ajax({
        url: HOST.concat("/IDCode"),
        type: "GET",
        success: function(datas){
            code = datas.data.IDCode;
            drawPic(code);
        },
        error: function(){
            console.log("请求验证码错误！");
        },
        dataType: "json",
    });
}

//下面就是判断是否== 的代码，无需解释
function validate(){
    removeCodeText();
    var result = "";
    var oValue = document.getElementById('codeInput').value.toUpperCase();

    if(oValue ==''||oValue==undefined){
        $("#codeInput").after("<span class='codeText' style='color:red'>&nbsp;请输入验证码</span>");
        return false;
    }else {
        $.ajax({
            url: HOST.concat("/checkIDCode?code="+oValue),
            type: "GET",
            async: false,
            success: function (datas) {
                result = datas.meta.state;
            },
            error: function(){
                console.log("请求验证码错误！");
            },
            dataType: "json",
        });
        if(result=='success'){
            return true;
        }else {
            $("#codeInput").after("<span class='codeText' style='color:red'>&nbsp;验证码不正确</span>");
            createCode();
            return false;
        }
    }
}

/**生成一个随机数**/
function randomNum(min,max){
    return Math.floor( Math.random()*(max-min)+min);
}
/**生成一个随机色**/
function randomColor(min,max){
    var r = randomNum(min,max);
    var g = randomNum(min,max);
    var b = randomNum(min,max);
    return "rgb("+r+","+g+","+b+")";
}


/**绘制验证码图片**/
function drawPic(IDCode){
    var canvas=document.getElementById("canvas");
    var width=canvas.width;
    var height=canvas.height;
    var ctx = canvas.getContext('2d');
    ctx.textBaseline = 'bottom';

    /**绘制背景色**/
    ctx.fillStyle = randomColor(180,240); //颜色若太深可能导致看不清
    ctx.fillRect(0,0,width,height);
    /**绘制文字**/

    /*   for(var i=0; i<4; i++){ */
    var txt = IDCode;
    ctx.fillStyle = randomColor(50,160);  //随机生成字体颜色
    ctx.font = randomNum(20,25)+'px SimHei'; //随机生成字体大小
    var x = 10;
    var y = randomNum(25,30);
    //修改坐标原点和旋转角度
    ctx.translate(x,y);
    ctx.fillText(txt, 0,0);
    //恢复坐标原点和旋转角度
    ctx.translate(-x,-y);
    /*    } */
    /* /**绘制干扰线**/
    for(var i=0; i<8; i++){
        ctx.strokeStyle = randomColor(40,180);
        ctx.beginPath();
        ctx.moveTo( randomNum(0,width), randomNum(0,height) );
        ctx.lineTo( randomNum(0,width), randomNum(0,height) );
        ctx.stroke();
    }
    /**绘制干扰点**/
    /*  for(var i=0; i<100; i++){
     ctx.fillStyle = randomColor(0,255);
     ctx.beginPath();
     ctx.arc(randomNum(0,width),randomNum(0,height), 1, 0, 2*Math.PI);
     ctx.fill();
     }  */
}
